package com.sillyhat.project.activiti.process.controller;

import com.sillyhat.project.activiti.config.builder.HeadlerBuilder;
import com.sillyhat.project.activiti.config.exception.BPMException;
import com.sillyhat.project.activiti.config.untils.ActivitiConstants;
import com.sillyhat.project.activiti.config.untils.ActivitiController;
import com.sillyhat.project.activiti.process.service.Headler;
import com.wordnik.swagger.annotations.ApiOperation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * ApplyProcessController
 *
 * @author 徐士宽
 * @date 2017/5/11 9:51
 */
@Controller
@RequestMapping("/apply-process")
public class ApplyProcessController extends ActivitiController {

    private final Logger logger = LoggerFactory.getLogger(ApplyProcessController.class);

    /**
     *
     * @param processCode   业务Code
     * @param processNode   流程节点
     * @return
     */
    @ApiOperation(value = "进入流程申请页面", response = String.class, notes = "进入流程申请页面")
    @RequestMapping(value = "/toStart", method = {RequestMethod.GET})
    public String toStart(@RequestParam("processCode") String processCode, @RequestParam("processNode")String processNode) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
        Headler headler = HeadlerBuilder.getProcessConfigService(processCode, processNode);
        Map<String, Object> params = new HashMap<String, Object>();
        try {
            //流程发起前
            headler.executeApplyBefore(context, request, params);
        } catch (BPMException e) {
            logger.error("executeApplyBefore Exception:",e);
        }

        //流程代码
        setAttribute("processCode", processCode);
        //流程节点
        setAttribute("processNode", processNode);
        //操作用户
//        setAttribute("currentUser", operator);
        //当前时间
        setAttribute("currentDate", new Date());
        try {
            //流程发起前后
            headler.executeApplyAfter(context, request, params);
        } catch (BPMException e) {
            logger.error("executeApplyAfter Exception:",e);
        }
        return "/process/" + processCode + "/Start";
    }
}
